package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;

    public static final short WM_NEWS_CONTENT_REFERENCE=1 ;//主图引用

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {

        //1:检查参数
        if(wmNewsPageReqDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNewsPageReqDto.checkParam();
        //2:dto查询

        IPage pageparam = new Page(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize()); //mybaitsplus构建分页条件

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper();

        //状态
        if(wmNewsPageReqDto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
        }

        //频道
        if(wmNewsPageReqDto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }

        //关键字
        if(wmNewsPageReqDto.getKeyword()!=null){
            lambdaQueryWrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }

        //时间区间
        if(wmNewsPageReqDto.getBeginPubDate()!=null && wmNewsPageReqDto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());
        }

        //查询自己的账号下发布的文章
        Integer userId = WmThreadLocalUtils.getUser().getId();
        if(userId ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId,userId);

        //排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        IPage page = page(pageparam, lambdaQueryWrapper);


        //3:封装结果
        ResponseResult responseResult =new PageResponseResult(wmNewsPageReqDto.getPage(),
                wmNewsPageReqDto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {

        //校验非空
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2：保存wmnews表
        WmNews wmNews = new WmNews();
        //对象拷贝 --- 深拷贝  浅拷贝
        BeanUtils.copyProperties(dto,wmNews);
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //[dfjksdjfdfj.jpg,sdlkjfskld.jpg]==>dfjksdjfdfj.jpg,sdlkjfskld.jpg
            wmNews.setImages(dto.getImages().toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));
        }
        this.saveWmNews(wmNews,isSubmit);


        //3：维护 wmNewsMaterial
        String content = dto.getContent(); //获取前端传递的内容信息
        List<Map> list= JSON.parseArray(content,Map.class); //json转集合
        List<String> materials = ectractUrlInfo(list);

        //3.1 解析图片  如果是1为提交审核  校验内容中的图片是否和素材库中的一致
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() != 0) {
            ResponseResult responseResult = saveRelativeInfoForContent(materials, wmNews.getId()); //指定的文章匹配素材
            if (responseResult != null) {
                return responseResult;
            }
        }

        //3.2 设置封面
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            ResponseResult responseResult = saveRelativeInfoForCover(dto, materials, wmNews);
            if (responseResult != null) {
                return responseResult;
            }
        }

        return null;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }

        //1:查询文章的状态 如果是上架的不能删除
        WmNews  wmNews= getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //9:已发布  enable 1：上架 0下架
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布或已上架，不能删除");
        }

        //2：先删关系表 再删文章表
        QueryWrapper<WmNewsMaterial> wrapper =new QueryWrapper<>();
        //wrapper.eq("newsId",wmNews.getId());
        wrapper.lambda().eq(WmNewsMaterial::getNewsId,wmNews.getId());
        wmNewsMaterialMapper.delete(wrapper);

        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //查询审核状态为8 且 发布时间小于当前时间
    @Override
    public List<Integer> findRelease() {
        QueryWrapper<WmNews> wrapper =new QueryWrapper<>();
        wrapper.lambda().eq(WmNews::getStatus,8).lt(WmNews::getPublishTime,new Date());
        List<WmNews> wmNewsList = wmNewsMapper.selectList(wrapper);

        //转换对象为泛型为integer的
        List<Integer> list = wmNewsList.stream().map(WmNews::getId).collect(Collectors.toList());

        return list;
    }

    @Override
    public ResponseResult findListAndPage(NewsAuthDto dto) {
        if(dto==null){
            return PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        }        //1.检查参数
        dto.checkParam();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //dto.setTitle("%"+dto.getTitle()+"%");

        //2.分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);
        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        WmNewsVo wmNewsVo = wmNewsMapper.findWmById(id);
        return wmNewsVo;
    }


    /**
     * 设置封面图片与素材的关系
     *
     * @param dto
     * @param materials
     * @param wmNews
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        List<String> images = dto.getImages();
        //自动匹配封面
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)) {
            //内容中的图片数量小于等于2  设置为单图
            if (materials.size() > 0 && materials.size() <= 2) {
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
            //修改文章信息
            if (images != null && images.size() > 0) {
                wmNews.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));

            }
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForImage(images, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    /**
     * @param images
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer newsId) {
        List<String> materials = new ArrayList<>();
        for (String image : images) {
            materials.add(image.replace(fileServerUrl,""));
        }

        return saveRelativeInfo(materials,newsId, WM_NEWS_CONTENT_REFERENCE);
    }

    /**
     * 保存素材与文章内容的关系
     *
     * @param materials
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        return saveRelativeInfo(materials, newsId, WM_NEWS_CONTENT_REFERENCE);
    }


    /**
     * 保存关系
     *
     * @param materials
     * @param newsId
     * @param type
     * @return
     */
    private ResponseResult saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //1.获取数据库中的素材信息
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);
        //2.通过图片的路径获取素材的id
        List<String> materialsIds = new ArrayList<>();
        if (dbMaterials != null && dbMaterials.size() > 0) {
            //<kdjfksdjkfljdsf.jps,2>
            Map<String, Integer> uriIdMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            for (String val : materials) {  //materials 文章中的图片
                String materialId = String.valueOf(uriIdMap.get(val));
                //没找到
                if ("null".equals(materialId)) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                }
                //找到了
                materialsIds.add(materialId);
            }
        }

        //3.批量保存数据
        wmNewsMaterialMapper.saveRelationsByContent(materialsIds, newsId, type);
        return null;
    }

    /**
     * 提取图片信息
     *
     * @param list
     * @return
     */
    private List<String> ectractUrlInfo(List<Map> list) {
        List<String> materials = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                materials.add(imgUrl);
            }
        }
        return materials;
    }



    /**
     * 保存或修改文章
     *
     * @param wmNews
     * @param isSubmit
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        boolean flag =false;
        if (wmNews.getId() == null) {
            flag = save(wmNews);
        } else {
            //如果是修改，则先删除素材与文章的关系
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            flag=updateById(wmNews);
        }

        //把文章id 作为消息放到消息队列  保证保存成功后发送消息
        if(flag){
            kafkaTemplate.send("wm.news.auto.scan.topic",JSON.toJSONString(wmNews.getId()));
        }
    }






}
